import ast
from enum import Enum
import logging
from logging.handlers import RotatingFileHandler
from typing import Any

from udsoncan import DidCodec, SecurityAlgoType

class CommonFunc:
    @staticmethod
    def InitLogging(Logname: str, Classname: str, Path: str = './', WriteConsole: bool = True) -> logging.Logger:
        logger = logging.getLogger(Classname)
        logger.setLevel(level=logging.DEBUG)
        
        handler = RotatingFileHandler(Path + Logname, maxBytes=10 * 1024 * 1024, backupCount=1)
        handler.setLevel(logging.DEBUG)
        
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s  - %(lineno)d - %(message)s')
        handler.setFormatter(formatter)
        
        if WriteConsole:
            console = logging.StreamHandler()
            console.setLevel(logging.DEBUG)
            logger.addHandler(console)
        
        logger.addHandler(handler)
        
        return logger
    
    def TurnStrtoEnum(self, inputstr:str, enumtype:Enum): 
        try: 
            return enumtype[inputstr]
        except Exception as e:
            raise KeyError("no thsi element{inputstr} in enum {enumtype} {e}")
    @staticmethod
    def convert_value(key: str, value: Any) -> Any:
        try:
            # 1. 自动识别布尔
            if isinstance(value, str) and value.lower() in ["true", "false"]:
                return value.lower() == "true"

            # 2. 自动识别16进制
            if isinstance(value, str) and value.lower().startswith("0x"):
                return int(value, 16)

            # 3. 针对配置项专门处理
            if key in ["request_timeout", "p2_timeout", "p2_star_timeout"]:
                v = float(value) if isinstance(value, str) else value
                return v / 1000.0

            elif key in ["dtc_snapshot_did_size", "server_address_format",
                        "server_memorysize_format", "standard_version"]:
                return int(value)

            # 4. 针对布尔配置
            elif key in ["exception_on_negative_response", "exception_on_invalid_response",
                        "exception_on_unexpected_response", "tolerate_zero_padding",
                        "ignore_all_zero_dtc", "use_server_timing"]:
                return bool(value) if isinstance(value, bool) else (value.lower() == 'true')

            # 5. 默认返回原值
            return value

        except Exception as e:
            print(f"Error converting value for {key}: {e}")
            return value

class ReadRemainingDataCodec(DidCodec):

    def encode(self, *args, **kwargs):
        return b''

    def decode(self, did_payload):
        return did_payload

    def __len__(self):
        raise self.ReadAllRemainingData


# logger.debug("This is a debug message with a parameter: %s", "parameter_value")